package com.lancoo.klgcourseware.ui.fragment.basicTrain;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewStub;
import android.widget.TextView;

import androidx.viewpager.widget.ViewPager;

import com.google.gson.Gson;
import com.lancoo.klgcourseware.R;
import com.lancoo.klgcourseware.entity.ExpressPracticeModel;
import com.lancoo.klgcourseware.entity.WordPracticeModel;
import com.lancoo.klgcourseware.entity.bean.KlgDbConstant;
import com.lancoo.klgcourseware.manager.KlgLocalMediaManager;
import com.lancoo.klgcourseware.manager.KlgMediaManager;
import com.lancoo.klgcourseware.ui.adapter.ViewPagerFragmentAdapter;
import com.lancoo.klgcourseware.ui.fragment.usage.SceneFragment;
import com.lancoo.klgcourseware.ui.fragment.usage.SentenceFragment;
import com.lancoo.klgcourseware.ui.fragment.usage.UsageSubBaseFragment;
import com.lancoo.klgcourseware.ui.widget.NoScrollViewPager;
import com.lancoo.klgcourseware.utils.klog.KLog;
import com.stkouyu.entity.LgEvaluateObj;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by pengmi on 2019/8/15 18:34
 * Description:用法训练
 */
public class UsageTrainFragment extends BasicTrainBaseFragment implements ViewPager.OnPageChangeListener ,KlgLocalMediaManager.OnPlayListener{

    private static final String TAG = "UsageTrainFragment";

    private List<ExpressPracticeModel> expressPracticeModelList;
    private int currentUsageIndex,demonstrationMusicIndex;
    private TextView tv_quesIndex,tv_quesTotal;
    private int speedState;//训练语速 0-慢 1-中 2-快
    private List<UsageSubBaseFragment> usageSubBaseFragmentList;
    private NoScrollViewPager viewPager;
    private KlgMediaManager demonstrationMediaManager;
    private KlgLocalMediaManager resultMediaManager;
    protected boolean isAutoStudy=true;
    private int usageScore,totalMediaLength;

    @Override
    protected int getContentViewId() {
        return R.layout.klg_fragment_usage_train;
    }

    @Override
    protected void initView(View view) {
        expressPracticeModelList = getArguments().getParcelableArrayList(KEY_USAGE_TRAIN);
        Log.e(TAG, "initView" );
        currentTrainTag=TRAINTAG_USAGE;
        if(expressPracticeModelList==null){
            showEmptyLayout();
        }else{
            enableStartTrain(0);
            initData(view);
        }
    }

    /**
     *开始训练 从3，2，1倒计时开始
     */
    protected void startTrain(){
        Log.e("John1","onTrainStart()");
        Log.e(TAG,"onTrainStart");
//        startTrainDialogCountTime();
        isAutoStudy=true;
        if(usageSubBaseFragmentList==null){
            return;
        }
        recorderProgress=0;
        usageSubBaseFragmentList.get(currentUsageIndex).startSentenceRecord();

    }

    private void initData(View view){
        ViewStub viewStub = view.findViewById(R.id.viewstub_main_data);
        if(viewStub!=null){
            viewStub.inflate();
        }
        resultMediaManager=new KlgLocalMediaManager();
        demonstrationMediaManager=new KlgMediaManager(getContext());
        tv_quesIndex = view.findViewById(R.id.tv_ques_index);
        tv_quesTotal = view.findViewById(R.id.tv_ques_total);
        upDateCurrentTrainIndex();
        viewPager = view.findViewById(R.id.viewpager);
        usageSubBaseFragmentList = new ArrayList<>();
        int index=0;
        for (ExpressPracticeModel expressPracticeModel:expressPracticeModelList){
            UsageSubBaseFragment usageSubBaseFragment=null;
            if(getArguments().getBoolean(KEY_IS_SCENE)){
                Log.e("aaaa","情景对话");
                usageSubBaseFragment=new SceneFragment();
            }else {
                Log.e("aaaa","读句填空");
                usageSubBaseFragment=new SentenceFragment();
            }
            usageSubBaseFragmentList.add(usageSubBaseFragment);
            Bundle bundle=new Bundle();
            bundle.putParcelable(UsageSubBaseFragment.KEY_EXPRESSPRACTICE,expressPracticeModel);
            bundle.putInt(UsageSubBaseFragment.KEY_QUESINDEX,index);
            bundle.putInt(UsageSubBaseFragment.KEY_ALERT,index<expressPracticeModelList.size()-1?R.string.klg_next_question:(getArguments().getBoolean(KEY_ISMORE_ENTER)?R.string.klg_result_exit_train_for_sentence_fill:(getArguments().getBoolean(KEY_ISLASTTRAINMODEL)?R.string.klg_train_result_page:R.string.klg_listen_repeat_page)));
            bundle.putInt(UsageSubBaseFragment.KEY_QUESTOTAL,expressPracticeModelList.size());
            bundle.putString(BasicTrainBaseFragment.KEY_KLGTYPE,getArguments().getString(BasicTrainBaseFragment.KEY_KLGTYPE));
            bundle.putBoolean(KEY_IS_ALERT,getArguments().getBoolean(KEY_IS_ALERT));
            usageSubBaseFragment.setArguments(bundle);
            index++;
        }
        ViewPagerFragmentAdapter mAdapter=new ViewPagerFragmentAdapter(getChildFragmentManager(), usageSubBaseFragmentList);
        viewPager.setAdapter(mAdapter);
        viewPager.setScroll(getArguments().getBoolean(KEY_ENABLE_TRAIN,true));
        tv_quesIndex.setVisibility(getArguments().getBoolean(KEY_ENABLE_TRAIN,true)?View.VISIBLE:View.INVISIBLE);
        tv_quesTotal.setVisibility(getArguments().getBoolean(KEY_ENABLE_TRAIN,true)?View.VISIBLE:View.INVISIBLE);
        viewPager.setOffscreenPageLimit(usageSubBaseFragmentList.size());
        viewPager.addOnPageChangeListener(this);
        SharedPreferences sp=getContext().getSharedPreferences(KlgDbConstant.SP_KNOWLEDGE_COURSE, Context.MODE_PRIVATE);
        speedState = sp.getInt(KlgDbConstant.SP_KEY_USAGE_SPEED, 1);

    }

    private void upDateCurrentTrainIndex(){
        if(tv_quesIndex==null||expressPracticeModelList==null){
            return;
        }
        tv_quesIndex.setText(String.format(getString(R.string.klg_usage_ques_index),(currentUsageIndex+1)));
        tv_quesTotal.setText(String.format(getString(R.string.klg_usage_ques_total),expressPracticeModelList.size()));
    }

    private void pauseMeidaPlayer(){
        if(resultMediaManager!=null){
            resultMediaManager.pause();
        }
        if(demonstrationMediaManager!=null){
            demonstrationMediaManager.pause();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        pauseMeidaPlayer();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(resultMediaManager!=null){
            resultMediaManager.release();
        }
        if(demonstrationMediaManager!=null){
            demonstrationMediaManager.release();
        }
    }

    @Override
    public void onComplete() {

    }

    @Override
    public void onStartError() {

    }

    @Override
    public void onPausePlay() {

    }

    @Override
    public void onSourceError() {

    }

    @Override
    public void onResumePlay() {

    }

    @Override
    public void onStopPlay() {

    }

    @Override
    public void onPrepare() {
        if(resultMediaManager!=null){
            resultMediaManager.start();
        }
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        pauseThreeSecondTimer();
        stopSpeechEvaluation(false);
        pauseTimer();
        pauseMeidaPlayer();
        pauseDripSoundPlay();
        pauseMeidaProgressTimer();
        pauseCurrentSubUsageTrain();
        currentUsageIndex=position;
        upDateCurrentTrainIndex();
        if(true){
            if(usageSubBaseFragmentList.get(currentUsageIndex).getIsQuality()){
                continueTrain();
            }else{
                startTrainDialogCountTime(0);
            }
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private void upDateSpeedAdjustState(int speedState){
        if(this.speedState==speedState){
            return;
        }
//        SharedPreferences sp=getContext().getSharedPreferences(KlgDbConstant.SP_KNOWLEDGE_COURSE, Context.MODE_PRIVATE);
//        SharedPreferences.Editor edit = sp.edit();
//        edit.putInt(KlgDbConstant.SP_KEY_USAGE_SPEED,speedState);
//        edit.commit();
//        this.speedState=speedState;
    }


    protected void playDemonstrationMusic(int musicIndex){
        if(expressPracticeModelList==null||demonstrationMediaManager==null){
            return;
        }
        if(musicIndex==0){
            totalMediaLength=0;
            startMeidaProgressTimer();
        }
        this.demonstrationMusicIndex=musicIndex;
        List<WordPracticeModel> oneSentenceList = expressPracticeModelList.get(currentUsageIndex).getOneSentenceList();
        if(musicIndex<oneSentenceList.size()){//假如当前的音频list下标<总音频数量,则进行音频播放
            demonstrationMediaManager.setUpMedia(KlgDbConstant.mediaUrl + oneSentenceList.get(musicIndex).getSenvoice(), new KlgMediaManager.OnPlayListener() {
                @Override
                public void onComplete() {
                    demonstrationMusicIndex++;
                    totalMediaLength+=demonstrationMediaManager.getDuring();
                    playDemonstrationMusic(demonstrationMusicIndex);
                }

                @Override
                public void onStartError() {
                    usageSubBaseFragmentList.get(currentUsageIndex).imgAninationStateChange(false);
                }

                @Override
                public void onPausePlay() {

                }

                @Override
                public void onSourceError() {
                    usageSubBaseFragmentList.get(currentUsageIndex).imgAninationStateChange(false);
                }

                @Override
                public void onResumePlay() {

                }

                @Override
                public void onStopPlay() {

                }

                @Override
                public void onPrepare() {
                    demonstrationMediaManager.start();
                    usageSubBaseFragmentList.get(currentUsageIndex).imgAninationStateChange(true);
                }

                @Override
                public void onBufferingUpdate(MediaPlayer mp, int percent) {

                }
            });
        }else{//否则结束当前分页中的音频播放
            Log.e("aaa","提示音播放完毕...");
            usageSubBaseFragmentList.get(currentUsageIndex).imgAninationStateChange(false);
            pauseMeidaProgressTimer();
//            continueTrain();
            playDripSoundMusic();
        }

    }


    protected void pauseCurrentSubTrain(boolean isReset){
        pauseMeidaPlayer();
        if(usageSubBaseFragmentList!=null){
            usageSubBaseFragmentList.get(currentUsageIndex).pauseTrain(isReset);
            if(isReset){
                isAutoStudy=false;
                for (UsageSubBaseFragment usageSubBaseFragment:usageSubBaseFragmentList){
                    usageSubBaseFragment.clearSubUsageTrainResult();
                }
                viewPager.setCurrentItem(0,false);
            }
        }
    }

    private void pauseCurrentSubUsageTrain(){
        if(usageSubBaseFragmentList!=null){
            usageSubBaseFragmentList.get(currentUsageIndex).pauseTrain(usageSubBaseFragmentList.get(currentUsageIndex).getSubUsaeTrainScore()<70);
        }
    }


    protected void onSuccessSpeechEvaluation(int grade, String url, LgEvaluateObj skegnResult){
        secondCountTime=REPEAT_TIME;
        if(usageSubBaseFragmentList==null){
            return;
        }
        usageSubBaseFragmentList.get(currentUsageIndex).speechEvaluationCallBack(grade,url,skegnResult);
    }


    protected void upDateRecordProgress(){

        if(usageSubBaseFragmentList==null){
            return;
        }
        usageSubBaseFragmentList.get(currentUsageIndex).recordProgressUpDate(recorderProgress);
    }

    //旧版，弃掉。。
    protected void upDateSecondCountTime(){
//        Log.e(TAG, "upDateSecondCountTime: "+secondCountTime );
//        if(secondCountTime==0){
//            pauseSecondTimer();
//        }
//        if(usageSubBaseFragmentList!=null){
//            usageSubBaseFragmentList.get(currentUsageIndex).upDateSecondTimer(secondCountTime);
//        }
    }

    //使用新版
    protected void upDateResultCountTime(int progress,int totalProgress){
        if(progress==totalProgress){
            pauseSecondTimer();
        }
        if(usageSubBaseFragmentList!=null){
            usageSubBaseFragmentList.get(currentUsageIndex).upDateSecondTimerProgress(progress,totalProgress);
        }
    }

    protected void startNextUsageQuesTrain(){
        if(usageSubBaseFragmentList!=null){
            if(currentUsageIndex<usageSubBaseFragmentList.size()-1){
                viewPager.setCurrentItem(currentUsageIndex+1,false);
            }else{
                Log.e("aaaa","完成用法训练作答");
                int correctNum=0;
                int studyScore=0;
                for (UsageSubBaseFragment usageSubBaseFragment:usageSubBaseFragmentList){
                    int score = usageSubBaseFragment.getSubUsaeTrainScore();
                    studyScore+=score;
                    if(score>=60){
                        correctNum++;
                    }
                }
                studyScore=studyScore/usageSubBaseFragmentList.size();
                usageScore = studyScore;
                enterNextTrainModel();
//                completeUsageTrain(correctNum,usageSubBaseFragmentList.size(),studyScore);
            }
//            usageSubBaseFragmentList.get(currentUsageIndex).upDateSecondTimer(secondCountTime);
        }
    }

    protected void quesResultMuiscPlayer(boolean isCorrect){
        int qualityCount=0;
        float grade=0;
        for (int i = 0; i < usageSubBaseFragmentList.size(); i++) {
           if(usageSubBaseFragmentList.get(i).getIsQuality()){
                qualityCount++;
            }
            grade+=usageSubBaseFragmentList.get(i).getGrade();
        }
        updateTrainResult(qualityCount*2>=usageSubBaseFragmentList.size(),grade/usageSubBaseFragmentList.size());
        if(resultMediaManager==null){
            return;
        }
        try {
            AssetFileDescriptor assetFileDescriptor = getContext().getAssets().openFd(isCorrect?"klg_record_correct.mp3":"klg_record_error.mp3");
            resultMediaManager.setUpMedia(assetFileDescriptor,this);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 继续训练
     */
    protected void continueTrain(){
        Log.e("aaaa","UsageTrainFragment,继续训练");
        if(usageSubBaseFragmentList!=null){
            usageSubBaseFragmentList.get(currentUsageIndex).resumeTrain();
        }
    }


    /**
     * 重新用法训练，擦除作答记录
     */
    protected void resetUsageTrain(){
        if(viewPager!=null){
            isAutoStudy=false;
//            if(usageScore<60){//上次作答不合格，重新训练语速退一档，最慢到慢速
//                if(speedState==2){
//                    upDateSpeedAdjustState(1);
//                }else if(speedState==1){
//                    upDateSpeedAdjustState(0);
//                }
//            }else{//上次作答合格，语速进一档，最快到中速
//                if(speedState==0){
//                    upDateSpeedAdjustState(1);
//                }
//            }
            for (UsageSubBaseFragment usageSubBaseFragment:usageSubBaseFragmentList){
                usageSubBaseFragment.clearSubUsageTrainResult();
            }
            viewPager.setCurrentItem(0,false);
            enableStartTrain(0);
        }
    }

    /**
     * 3s倒计时，更新进度样式
     * @param progress
     * @param totalProgress
     */
    protected void updateCountTime(int progress,int totalProgress){

        if(convertView==null){
            return;
        }
        if(usageSubBaseFragmentList!=null){
            usageSubBaseFragmentList.get(currentUsageIndex).updateCountTimeProgress(progress,totalProgress);
        }
//        Log.e("aaaaa","currentUsageIndex"+currentUsageIndex+"....progress:"+progress+"......>"+totalProgress);
//        convertView.findViewById(R.id.rl_count_time).setVisibility(progress==totalProgress?View.GONE:View.VISIBLE);
//        countTimeView.setAngle(progress,totalProgress);
    }

    protected void updateMediaPlayerProgress(){
        if(usageSubBaseFragmentList!=null&&demonstrationMediaManager!=null){
            usageSubBaseFragmentList.get(currentUsageIndex).updateMediaPlayProgress(totalMediaLength+(demonstrationMediaManager.isPrepared()?demonstrationMediaManager.getCurrentPosition():0));
        }
    }

}
